<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>JSON Rank Parser</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8f9fb;
            padding: 40px;
            color: #333;
        }

        h2 {
            color: #2c3e50;
        }

        textarea {
            width: 100%;
            height: 240px;
            font-family: monospace;
            font-size: 14px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 6px;
            box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.1);
            background-color: #fff;
        }

        button {
            margin: 10px 10px 10px 0;
            padding: 10px 20px;
            font-size: 15px;
            background-color: #2980b9;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }

        button:hover {
            background-color: #1f6691;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 30px;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
        }

        th, td {
            padding: 12px;
            text-align: center;
        }

        th {
            background-color: #34495e;
            color: white;
        }

        tr:nth-child(even) {
            background-color: #f0f4f8;
        }

        .example {
            margin: 10px 0;
            font-size: 14px;
            background: #eef2f7;
            padding: 10px;
            border-left: 4px solid #3498db;
        }

        #copyArea {
            margin-top: 30px;
        }

        .copy-group {
            display: flex;
            gap: 20px;
            margin-top: 10px;
        }

        .copy-group textarea {
            width: 100%;
            height: 100px;
        }

        label {
            font-weight: 600;
        }
    </style>
</head>
<body>
<h2>JSON Element & Score 排名解析器</h2>

<div class="example">
    示例 JSON：<br>
    <code>[
        { "element": "1861067319493816320", "score": 2.7208309548257184E9 },
        { "element": "1861306548017463296", "score": 2.1930883958257184E9 }
        ]</code>
</div>

<label for="jsonInput">请输入 JSON 数据：</label><br>
<textarea id="jsonInput" placeholder='粘贴 [{"element": "...", "score": ...}, ...] 格式的数据'></textarea>
<br>
<button onclick="formatJSON()">格式化</button>
<button onclick="parseJSON()">解析并展示</button>
<button onclick="exportToExcel()">导出 Excel</button>

<div id="outputArea">
    <table id="outputTable" style="display:none;">
        <thead>
        <tr>
            <th>排名</th>
            <th>Element</th>
            <th>Score</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<div id="copyArea">
    <label>提取结果（可复制）：</label><br>
    <div class="copy-group">
        <textarea id="elementOutput" readonly placeholder="Element 列"></textarea>
        <textarea id="scoreOutput" readonly placeholder="Score（整数）列"></textarea>
    </div>
</div>

<script>
    function formatJSON() {
        try {
            const input = document.getElementById('jsonInput').value;
            const parsed = JSON.parse(input);
            const formatted = JSON.stringify(parsed, null, 2);
            document.getElementById('jsonInput').value = formatted;
        } catch (e) {
            alert("格式化失败，请确认是合法的 JSON。\n\n错误信息：" + e.message);
        }
    }

    function parseJSON() {
        const input = document.getElementById('jsonInput').value;
        const table = document.getElementById('outputTable');
        const tbody = table.querySelector('tbody');
        const elementOutput = document.getElementById('elementOutput');
        const scoreOutput = document.getElementById('scoreOutput');

        tbody.innerHTML = '';
        elementOutput.value = '';
        scoreOutput.value = '';

        try {
            const data = JSON.parse(input);

            // 按 score 降序排序
            const sorted = data
                .filter(item => item.element && typeof item.score === 'number')
                .sort((a, b) => b.score - a.score);

            const elements = [];
            const scores = [];

            sorted.forEach((item, index) => {
                const tr = document.createElement('tr');

                const tdRank = document.createElement('td');
                tdRank.textContent = index + 1;
                tr.appendChild(tdRank);

                const tdElement = document.createElement('td');
                tdElement.textContent = item.element;
                tr.appendChild(tdElement);

                const tdScore = document.createElement('td');
                const intScore = Math.floor(item.score);
                tdScore.textContent = intScore;
                tr.appendChild(tdScore);

                tbody.appendChild(tr);

                elements.push(item.element);
                scores.push(intScore);
            });

            elementOutput.value = elements.join('\n');
            scoreOutput.value = scores.join('\n');
            table.style.display = 'table';

        } catch (err) {
            alert('JSON 格式有误，请检查输入！\n\n错误信息：' + err.message);
            table.style.display = 'none';
        }
    }

    function exportToExcel() {
        const elementLines = document.getElementById('elementOutput').value.split('\n');
        const scoreLines = document.getElementById('scoreOutput').value.split('\n');

        if (elementLines.length === 0 || scoreLines.length === 0 || elementLines.length !== scoreLines.length) {
            alert('无可导出的数据，或两列数据数量不一致。');
            return;
        }

        const worksheetData = [["Element", "Score"]];
        for (let i = 0; i < elementLines.length; i++) {
            worksheetData.push([elementLines[i], parseInt(scoreLines[i])]);
        }

        const worksheet = XLSX.utils.aoa_to_sheet(worksheetData);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

        XLSX.writeFile(workbook, "json_elements.xlsx");
    }
</script>
</body>
</html>
